﻿
#include "common.h"

int get_sock(u8 *ip, u32 port) 
{
    int fd = 0;
    int opt = 1;
    int ret = 0;
    struct sockaddr_in server_addr;

    memset(&server_addr, 0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(port);

    fd = socket(AF_INET, SOCK_STREAM, 0);

    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    ret = bind(fd, (struct sockaddr *) &server_addr, sizeof(server_addr));
    if (ret < 0) {
        perror("bind failed!");
		exit(EXIT_FAILURE);
    }

    ret = listen(fd, BACKLOG);
    if (ret < 0) {
        perror("listen failed!");
		exit(EXIT_FAILURE);
    }

    return fd;
}

int get_connfd(int listenfd)
{
    int connfd;
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);

    if ((connfd = accept(listenfd, (struct sockaddr *) &client_addr, &client_len)) < 0) {
        perror("accept failed!");
		exit(EXIT_FAILURE);
    }

    return connfd;
}
